$(document).ready(function() {
    let riskAssessments = [];
    let portfolios = [];
    let totalPages = 1;
    let currentPage = 1;
    let itemsPerPage = 10;

    // 自定义alert函数
    function customAlert(message) {
        $('#customAlertMessage').text(message);
        $('#customAlertModal').modal('show');
    }

    // 获取所有投资组合用于下拉列表
    function fetchPortfolios() {
        $.ajax({
            url: `/api/portfolios/getAllPortfolios`,
            type: 'GET',
            success: function(data) {
                portfolios = data;
                renderPortfolioSelects();
            },
            error: function(xhr, status, error) {
                console.error('Error fetching portfolios:', error);
            }
        });
    }

    function renderPortfolioSelects() {
        const searchSelect = $('#searchPortfolioId');
        const addSelect = $('#addPortfolioId');
        const editSelect = $('#editPortfolioId');
        
        searchSelect.empty();
        addSelect.empty();
        editSelect.empty();
        
        searchSelect.append('<option value="">全部组合</option>');
        addSelect.append('<option value="">请选择</option>');
        editSelect.append('<option value="">请选择</option>');
        
        portfolios.forEach(portfolio => {
            searchSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
            addSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
            editSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
        });
    }

    function fetchRiskAssessments() {
        const fundCode = $('#searchFundCode').val();
        const portfolioId = $('#searchPortfolioId').val();
        const riskLevel = $('#searchRiskLevel').val();
        itemsPerPage = parseInt($('#itemsPerPage').val(), 10);
        const queryParams = {
            fundCode: fundCode || '',
            portfolioId: portfolioId || '',
            riskLevel: riskLevel || '',
            pageNo: currentPage,
            pageSize: itemsPerPage
        };

        $.ajax({
            url: `/api/riskAssessments/getRiskAssessmentsByConditions`,
            type: 'GET',
            data: queryParams,
            success: function(data) {
                if (!data || !data.records) {
                    console.error('Invalid data received:', data);
                    customAlert('获取数据失败，请检查输入条件或稍后重试。');
                    return;
                }

                riskAssessments = data.records;
                totalPages = data.pages;
                renderRiskAssessmentTable(riskAssessments);
                updatePagination();
            },
            error: function(xhr, status, error) {
                console.error('Error fetching risk assessments:', error);
                customAlert('获取数据失败，请检查网络连接或稍后重试。');
            }
        });
    }

    function renderRiskAssessmentTable(data) {
        const riskAssessmentTableBody = $('#riskAssessmentTableBody');
        riskAssessmentTableBody.empty();

        if (data.length > 0) {
            data.forEach(assessment => {
                const tr = $('<tr>');
                tr.append($('<td>').text(assessment.fundCode || ''));
                tr.append($('<td>').text(assessment.portfolioName || ''));
                tr.append($('<td>').text(assessment.riskLevelName));
                tr.append($('<td>').text(assessment.volatility ? assessment.volatility.toFixed(4) : ''));
                tr.append($('<td>').text(assessment.maxDrawdown ? assessment.maxDrawdown.toFixed(4) : ''));
                tr.append($('<td>').text(assessment.sharpeRatio ? assessment.sharpeRatio.toFixed(4) : ''));
                tr.append($('<td>').text(assessment.createdTime || ''));
                
                const actionsTd = $('<td>');
                actionsTd.html(`
                    <button class="btn btn-sm btn-warning me-2" onclick="editRiskAssessment(${assessment.id})">编辑</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteRiskAssessment(${assessment.id})">删除</button>
                `);
                tr.append(actionsTd);
                riskAssessmentTableBody.append(tr);
            });
        } else {
            riskAssessmentTableBody.html('<tr><td colspan="8" class="text-center">暂无数据</td></tr>');
        }
    }

    // 更新分页控件
    function updatePagination() {
        // 更新页码显示
        $('#currentPage').text(currentPage);
        $('#totalPages').text(totalPages);
        
        // 更新上一页和下一页按钮状态
        if (currentPage <= 1) {
            $('#prevPage').addClass('disabled');
        } else {
            $('#prevPage').removeClass('disabled');
        }
        
        if (currentPage >= totalPages) {
            $('#nextPage').addClass('disabled');
        } else {
            $('#nextPage').removeClass('disabled');
        }
    }

    function handleSizeChange(newSize) {
        itemsPerPage = newSize;
        currentPage = 1; // 重置到第一页
        fetchRiskAssessments();
    }

    function handleCurrentChange(newPage) {
        // 确保页码在有效范围内
        if (newPage < 1) newPage = 1;
        if (newPage > totalPages) newPage = totalPages;
        
        if (newPage !== currentPage) {
            currentPage = newPage;
            fetchRiskAssessments();
        }
    }

    function addNewRiskAssessment() {
        const fundCode = $('#addFundCode').val();
        const portfolioId = $('#addPortfolioId').val();
        const riskLevel = $('#addRiskLevel').val();
        const volatility = $('#addVolatility').val();
        const maxDrawdown = $('#addMaxDrawdown').val();
        const sharpeRatio = $('#addSharpeRatio').val();

        if (riskLevel === '') {
            customAlert('风险等级不能为空');
            return;
        }

        const newRiskAssessment = {
            fundCode: fundCode || null,
            portfolioId: portfolioId || null,
            riskLevel: riskLevel,
            volatility: volatility || null,
            maxDrawdown: maxDrawdown || null,
            sharpeRatio: sharpeRatio || null
        };

        $.ajax({
            url: `/api/riskAssessments/addRiskAssessment`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(newRiskAssessment),
            success: function(data) {
                $('#addRiskAssessmentForm')[0].reset();
                $('#addRiskAssessmentModal').modal('hide');
                fetchRiskAssessments();
                customAlert('新增成功');
            },
            error: function(xhr, status, error) {
                console.error('Error adding risk assessment:', error);
                customAlert('新增风险评估失败');
            }
        });
    }

    function saveEditRiskAssessment() {
        const riskAssessmentId = $('#editRiskAssessmentId').val();
        const fundCode = $('#editFundCode').val();
        const portfolioId = $('#editPortfolioId').val();
        const riskLevel = $('#editRiskLevel').val();
        const volatility = $('#editVolatility').val();
        const maxDrawdown = $('#editMaxDrawdown').val();
        const sharpeRatio = $('#editSharpeRatio').val();

        if (riskLevel === '') {
            customAlert('风险等级不能为空');
            return;
        }

        const updatedRiskAssessment = {
            id: riskAssessmentId,
            fundCode: fundCode || null,
            portfolioId: portfolioId || null,
            riskLevel: riskLevel,
            volatility: volatility || null,
            maxDrawdown: maxDrawdown || null,
            sharpeRatio: sharpeRatio || null
        };

        $.ajax({
            url: `/api/riskAssessments/updateRiskAssessment`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(updatedRiskAssessment),
            success: function(data) {
                $('#editRiskAssessmentModal').modal('hide');
                fetchRiskAssessments();
                customAlert('信息更新成功');
            },
            error: function(xhr, status, error) {
                console.error('Error updating risk assessment:', error);
                customAlert('更新风险评估失败');
            }
        });
    }

    function deleteRiskAssessment(id) {
        if (confirm('确定要删除该风险评估吗？')) {
            $.ajax({
                url: `/api/riskAssessments/deleteRiskAssessment/${id}`,
                type: 'POST',
                success: function() {
                    fetchRiskAssessments();
                    customAlert('删除成功');
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting risk assessment:', error);
                    customAlert('删除风险评估失败');
                }
            });
        }
    }

    // 全局函数供HTML调用
    window.editRiskAssessment = function(id) {
        const assessment = riskAssessments.find(p => p.id == id);
        if (assessment) {
            $('#editRiskAssessmentId').val(assessment.id);
            $('#editFundCode').val(assessment.fundCode || '');
            $('#editPortfolioId').val(assessment.portfolioId || '');
            $('#editRiskLevel').val(assessment.riskLevel);
            $('#editVolatility').val(assessment.volatility || '');
            $('#editMaxDrawdown').val(assessment.maxDrawdown || '');
            $('#editSharpeRatio').val(assessment.sharpeRatio || '');
            $('#editRiskAssessmentModal').modal('show');
        }
    };

    window.deleteRiskAssessment = deleteRiskAssessment;

    // 事件绑定
    $('#fetchRiskAssessmentsButton').on('click', fetchRiskAssessments);
    $('#saveAddRiskAssessment').on('click', addNewRiskAssessment);
    $('#saveEditRiskAssessment').on('click', saveEditRiskAssessment);

    $('#itemsPerPage').on('change', function() {
        handleSizeChange(parseInt($(this).val(), 10));
    });

    $('#pPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage > 1) {
            handleCurrentChange(currentPage - 1); 
        }
    });
    
    $('#nPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage < totalPages) {
            handleCurrentChange(currentPage + 1); 
        }
    });

    // 初始化
    fetchPortfolios();
    fetchRiskAssessments();
});